home *** CD-ROM | disk | FTP | other *** search
- Path: newsfeed.direct.ca!usenet
- From: qjackson@direct.ca
- Newsgroups: comp.lang.c++
- Subject: Re: What does this "const" mean?
- Date: Wed, 28 Feb 1996 16:51:17 GMT
- Organization: Parsepolis Software
- Message-ID: <4h218d$2ar@aphex.direct.ca>
- References: <4h0j7u$htp@crcnis3.unl.edu>
- Reply-To: qjackson@direct.ca
- NNTP-Posting-Host: 204.174.249.137
- X-Newsreader: Forte Free Agent 1.0.82
-
- chijang@cse.unl.edu (Chi-Jang Huang) wrote:
-
- > class intset {
- > // ...
- > void start(int& i) const { i = 0; }
- > int ok(int& i) const { return i<cursize; }
- > int next(int& i) const { return x[i++]; }
- > };
-
- > What does "const" mean in this program segment? What role does
- >it play? In what kind of situation will we use "const" like this?
- >Any comments or suggestions are highly appreciated. Thanks.
-
- When a member function is declared const, it is flagged by the
- compiler as being known not to change any member data of the class.
- Only const member functions can be invoked with const objects. For
- instance:
-
- class foo
- {
- public:
- int quux;
-
- // bar does not change quux
- void bar (void) const { /* ... */ }
-
- // baz can change quux, if it has to
- void baz (void) {/* .... */}
-
- };
-
- const foo someFoo;
-
- someFoo.bar(); // LEGAL becase someFoo and bar are both const
-
- someFoo.baz(); // ILLEGAL because someFoo is const,
- // and baz isn't
-
- From what I've seen of C++ code, const member functions are used
- primarily as member functions whose main purpose is to return the
- value of member data members, or the value of calculations made on
- member data members. They can also be used to change the value of one
- or more of their parameters according to some internal logic of the
- class, as in the case of intset::next(int& i) in your snippet.
-
- The only "suggestion" I can make is to declare any member function
- that does not alter any of its class's member data members as const,
- since this will free up as many of the member functions for use by
- objects declared as const as possible.
-
-
- Hope that helps....
-
-
-
- --
- |
- Parsepolis Software | Quinn Tyler Jackson
- "ParseCity" | (aka 'Jamshid')
- >--------------------------| qjackson@direct.ca
- |---------------------->
-
-